package com.yk.system.controller;

import cn.hutool.core.collection.CollUtil;
import com.yk.api.dataGatherer.dto.CustomDTO;
import com.yk.api.dataGatherer.dto.DeviceParamDTO;
import com.yk.api.dataGatherer.dto.VariableParamDTO;
import com.yk.common.core.constant.NumberConstant;
import com.yk.common.core.domain.Result;
import com.yk.common.core.utils.LoginHelper;
import com.yk.common.rabbitmq.constant.QueueConstants;
import com.yk.system.entity.ExcelHistory;
import com.yk.system.service.ExcelHistoryService;
import io.swagger.annotations.Api;
import io.swagger.annotations.ApiOperation;
import lombok.RequiredArgsConstructor;
import lombok.extern.slf4j.Slf4j;
import org.springframework.amqp.core.AmqpTemplate;
import org.springframework.web.bind.annotation.PostMapping;
import org.springframework.web.bind.annotation.RequestBody;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RestController;

import java.util.Objects;
import java.util.stream.Collectors;

/**
 * 自定义报表 yk-system
 *
 * @author lmx
 * @date 2023/11/16 15:28
 */
@RestController
@RequestMapping("/customExcel")
@Api(tags = "自定义报表")
@RequiredArgsConstructor
@Slf4j
public class CustomExcelController {

    private final AmqpTemplate amqpTemplate;
    private final ExcelHistoryService excelHistoryService;

    @ApiOperation("导出")
    @PostMapping("/customExcel")
    public Result<Void> customExcel(@RequestBody CustomDTO customDTO) {
        if (Objects.isNull(customDTO) || CollUtil.isEmpty(customDTO.getDevices()) || CollUtil.isEmpty(customDTO.getVariables())) {
            return Result.fail("请选择设备和变量");
        }
        customDTO.setCreatedBy(LoginHelper.getLoginUserId());
        String dataSource = customDTO.getDevices().stream().map(DeviceParamDTO::getDeviceName).collect(Collectors.joining("、"));
        String dataRadius = customDTO.getVariables().stream().map(VariableParamDTO::getName).collect(Collectors.joining("、"));
        ExcelHistory excelHistory = excelHistoryService.saveExcelHistory(customDTO.getExcelName(), dataSource,
                dataRadius, customDTO.getStartTime(), customDTO.getEndTime(), customDTO.getCreatedBy(), NumberConstant.ZERO_STR);
        customDTO.setExcelHistoryId(excelHistory.getId());
        amqpTemplate.convertAndSend(QueueConstants.REPORT_EXPORT, customDTO);
        return Result.ok();
    }
}
